<template>
  <div>
    <div
      class="imageUploadBox"
      v-viewer
      :style="{
        gridTemplateColumns: `repeat(auto-fill, minmax(${width}, ${width}))`,
      }"
    >
      <template v-if="imageList.length >= 1">
        <template v-for="(item, index) in imageList" :key="index">
          <div class="imagebox" :style="{ width, height, borderRadius }">
            <a-image
              class="imageItem"
              :preview="false"
              :style="{ width, height, borderRadius, objectFit: 'cover' }"
              :src="item.ossPath"
            />
            <div class="handleMsak">
              <span
                class="icon-[mdi--eye-outline] text-xl text-white"
                @click="previewImg(index)"
              ></span>
              <span class="text-xl">&nbsp;</span>
              <span class="text-xl">&nbsp;</span>
              <span
                class="icon-[mdi--delete-outline] text-xl text-white"
                @click="deleteImg(index)"
              ></span>
            </div>
          </div>
        </template>
      </template>
      <template v-if="imageList.length < maxCount">
        <Upload
          v-model:file-list="fileList"
          list-type="picture-card"
          class="imageUploader"
          accept="image/*"
          name="file"
          :style="{ width, height }"
          :show-upload-list="false"
          :action="uploadApiUrl"
          :headers="headers"
          :data="data"
          :maxCount="maxCount"
          :multiple="multiple"
          @change="handleChange"
        >
          <div>
            <span class="icon-[mdi--arrow-expand-up]"></span>
            <div class="ant-upload-text">上传</div>
          </div>
        </Upload>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'ImageUpload',
});
import { useAccessStore } from '@vben/stores';
import { Upload, message } from 'ant-design-vue';
import type { UploadChangeParam, UploadProps, Image } from 'ant-design-vue';
import { uploadApiUrl } from '#/api/index';
import { ref, watch, computed, onMounted } from 'vue';
import { previewImgObject } from '#/utils/tools';

const fileList = ref([]);
const imageList = ref<any[]>([]);
const loading = ref<boolean>(false);

const props = defineProps({
  modelValue: {
    type: [String, Number, Array],
    default: undefined,
  },
  data: {
    type: Object,
    default: () => {
      return {
        biz: 'temp',
      };
    },
  },
  width: {
    type: String,
    default: '100px',
  },
  height: {
    type: String,
    default: '100px',
  },
  borderRadius: {
    type: String,
    default: '10px',
  },
  maxCount: {
    type: Number,
    default: 1,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['update:modelValue']);

watch(
  () => props.modelValue,
  (newValue) => {
    console.log('props.modelValue', props.modelValue);
    if (!props.modelValue) return;
    if (imageList.value.length > 0) return;
    if (props.maxCount > 1) {
      console.log('maxCount', props.maxCount);
    } else {
      imageList.value.push({
        ossPath: props.modelValue,
      });
    }
  },
  { once: true },
);

const headers = computed(() => {
  return {
    Authorization: useAccessStore()?.accessToken as string,
  };
});

// 上传图片变动
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    console.log('customRequest', info);
    console.log('customRequest', fileList.value);
    if (info.file.response?.code == 100) {
      const imageData: any = info.file.response?.data;
      imageList.value.push(imageData);
      message.success('上传成功');
    }
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('上传失败，请稍后重试');
  }
  updateData();
};

// 更新组件数据
const updateData = () => {
  if (imageList.value.length == 0) return;
  if (props.maxCount == 1) {
    emit('update:modelValue', imageList.value[0]['ossPath']);
  } else {
    emit('update:modelValue', imageList.value);
  }
};

const beforeUpload = (file: any) => {
  console.log('customRequest', file);
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

// 预览图片
const previewImg = (index: number) => {
  const url = 'ossPath';
  const images = [...imageList.value];
  previewImgObject({ url, index, images });
};
// 删除图片
const deleteImg = (index: number) => {
  imageList.value.splice(index, 1);
  fileList.value.splice(index, 1);
};
</script>

<style lang="scss" scoped>
.imageUploadBox {
  display: grid;
  gap: 10px;
}
.imagebox {
  position: relative;
  cursor: pointer;
  overflow: hidden;
  &:hover {
    .handleMsak {
      opacity: 1;
    }
  }
}
.imageItem {
  position: relative;
  display: inline-block;
  z-index: 1;
}
.handleMsak {
  opacity: 0;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  position: absolute;
  background: #00000070;
  z-index: 2;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  transition: all 0.3s linear;
}
</style>
